<template>
	<view class="content">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-title">购物车</view>
			<view class="manage-button" @click="toggleEditMode">{{ isEditMode ? '完成' : '管理' }}</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-item" v-for="(item, index) in shoppingList" :key="index">
			<radio :value="String(item.id)" :checked="item.selected" @click="toggleSelection(item)"></radio>
			<image class="goods-image" :src="item.commodityDto.pictureIntegrationDtoS[0].pictureUrl" mode="aspectFill">
			</image>
			<view class="goods-info">
				<p class="title">{{ item.commodityDto.commodityName }}</p>
				<p class="tags">{{ formatTags(item) }}</p>
				<view class="count-price">
					<p class="price">
						￥{{ item.commoditySpecificationBasicInformationDto.commoditySpecificationAttributeInfoDto.sellingPrice }}
					</p>
					<!-- v-if="!isEditMode" -->
					<view class="count">
						<button style="width: 20rpx;background-color: transparent;" size="mini"
							@click="decreasecount(item)">-</button>
						<input type="number" v-model="item.count" />
						<button style="width: 20rpx;background-color: transparent;" size="mini"
							@click="increasecount(item)">+</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottomBox" v-if="shoppingList.length>0">
			<radio :checked="isAllSelected" @click="selectAll($event)"></radio>
			<view class="leftButton" @click="selectAll($event)">
				全选
			</view>
			<view class="rightButton" @click="handleBottomButtonClick">
				{{ isEditMode ? '删除' : '去结算' }}
			</view>
		</view>

		<!-- 购物车为空时显示 -->
		<view v-if="!shoppingList.length">
			<image style="margin:10%;" src='../../static/null/null.png'></image>
		</view>
	</view>
</template>
<script>
	import {
		getShopping,
		editShopping,
		deleteShopping
	} from '@/api/order.js';

	export default {
		data() {
			return {
				shoppingList: [],
				isEditMode: false,
			};
		},
		computed: {
			isAllSelected() {
				return this.shoppingList.length > 0 && this.shoppingList.every(item => item.selected);
			}
		},
		onShow() {
			this.getShoppingList();
		},
		methods: {
			getShoppingList() {
				const data = {
					pageSize: 99,
					pageNumber: 1
				};
				getShopping(data).then(res => {
					this.shoppingList = res.data.records.map(item => ({
						...item,
						selected: false
					}));
				});
			},
			toggleSelection(item) {
				item.selected = !item.selected;
			},
			selectAll(event) {
				event.stopPropagation(); // 阻止事件冒泡
				const newState = !this.isAllSelected;
				this.shoppingList.forEach(item => item.selected = newState);
			},
			decreasecount(item) {
				if (item.count > 1) {
					item.count--;
					this.updateShoppingItem(item);
				}
			},
			increasecount(item) {
				item.count++;
				this.updateShoppingItem(item);
			},
			updateShoppingItem(item) {
				const data = {
					...item
				};
				editShopping(data).then(() => this.getShoppingList()).catch(err => console.error('Update failed:', err));
			},
			handleBottomButtonClick() {
				if (this.isEditMode) {
					this.deleteSelectedItems();
				} else {
					this.checkout();
				}
			},
			checkout() {
				const selectedItems = this.shoppingList.filter(item => item.selected);
				const selectedIds = selectedItems.map(item => item.id);
				const idsString = encodeURIComponent(JSON.stringify(selectedIds));
				if (selectedItems.length>0) {
					uni.navigateTo({
						url: `/pages/classification/addOrder/index?selectedIds=${idsString}&type=购物车`
					});
				}
			},
			deleteSelectedItems() {
				// 收集所有选中的项
				const selectedItems = this.shoppingList.filter(item => item.selected);

				if (selectedItems.length === 0) {
					uni.showToast({
						title: '未选择任何项目',
						icon: 'none'
					});
					return;
				}

				// 提取选中项的ID并转换为逗号分隔的字符串
				const selectedIds = selectedItems.map(item => item.id);
				console.log(selectedIds, "selectedIds");

				// 调用删除购物项的API，确保传递的是未经编码的字符串或数组
				deleteShopping(selectedIds).then(res => {
					uni.showToast({
						title: '删除成功',
					});

					// 刷新购物列表
					this.getShoppingList();
				}).catch(error => {
					console.error('删除失败:', error);
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					});
				});
			},
			toggleEditMode() {
				this.isEditMode = !this.isEditMode;
			},
			// formatTags(item) {
			// 	const spec = item.commoditySpecificationBasicInformationDto;
			// 	return `${spec.attributeName}: ${spec.attributeValue}, ${spec.commoditySpecificationAttributeInfoDto.specificationName}: ${spec.commoditySpecificationAttributeInfoDto.specificationValue}`;
			// }
			formatTags(item) {
				const spec = item.commoditySpecificationBasicInformationDto || {};
				const attributeName = spec.attributeName || '';
				const attributeValue = spec.attributeValue || '';
				const specification = spec.commoditySpecificationAttributeInfoDto || {};
				const specificationName = specification.specificationName;
				const specificationValue = specification.specificationValue;

				// 构建基础的标签文本
				let tagsText = `${attributeName}: ${attributeValue}`;

				// 如果 specificationName 和 specificationValue 都不为 null 或 undefined 且非空字符串，则追加到标签文本
				if (specificationName && specificationValue && specificationName !== '' && specificationValue !== '') {
					tagsText += `, ${specificationName}: ${specificationValue}`;
				}

				return tagsText;
			}
		}
	};
</script>
<style lang="scss">
	@import '@/uni.scss'; // 导入全局 SCSS 变量文件

	.content {
		min-height: 100vh;
		background-color: #F3F3F3;
		position: relative;
		padding-top: 1rpx;
	}

	.custom-navbar {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: $uni-bg-color-white;
		border-bottom: 1rpx solid #e5e5e5;

		.navbar-title {
			text-align: center;
			width: 56%;
			text-align: right;
			margin-top: 20rpx;
		}

		.manage-button {
			width: 24%;
			color: red;
			font-size: 28rpx;
			margin-top: 20rpx;
			text-align: center;
			margin-right: 20%;
		}
	}

	.goods-item {
		display: flex;
		align-items: center;
		background-color: $uni-bg-color-white;
		margin: 20rpx 20rpx;
		padding: 20rpx 20rpx;
		border-radius: 20rpx;
	}

	.goods-image {
		width: 200rpx;
		height: 200rpx;
		margin-right: 20rpx;
	}

	.goods-info {
		flex: 1;
	}

	.title {
		height: 80rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: $uni-text-color;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tags {
		font-size: $uni-font-size-sm;
		color: $uni-text-color-grey;
		margin-top: 5rpx;
	}

	.count-price {
		display: flex;
		padding-top: 40rpx;
	}

	.price {
		width: 200rpx;
		font-size: 18px;
		color: #e4393c;
		margin-top: 5px;
	}

	.count {
		display: flex;
		height: 60rpx;
		border: 2rpx solid #999;
		border-radius: 60rpx;

		input {
			width: 60rpx;
			height: 60rpx;
			text-align: center;
			border-left: 2rpx solid #999;
			border-right: 2rpx solid #999;
		}

		/deep/uni-button:after {
			border: none !important;
		}
	}

	.bottomBox {
		width: 100%;
		height: 100rpx;
		position: fixed;
		bottom: 120rpx;
		z-index: 1000;
		background-color: $uni-color-fff;
		display: flex;

		/deep/radio {
			margin: 26rpx 0rpx 10rpx 30rpx;
		}

		.leftButton {
			width: 10%;
			text-align: center;
			line-height: 100rpx;
			color: $uni-text-color-grey;
		}

		.rightButton {
			width: 30%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: $uni-color-orange;
			color: white;
			border-radius: 80rpx;
			margin: 10rpx 0rpx;
			margin-left: 50%;
		}
	}
</style>